<?php

namespace app\common\logic;



use app\admin\model\Leeaddress;
use app\common\validate\leescore\AddressValidate;
use fast\Http;
use think\Db;
use think\exception\ValidateException;

/**
 * Token接口
 */
class AddressLogic
{
    //地址模型
    protected $addressModel = null;
    protected $key = '';
    private $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
    public function __construct()
    {
        $this->addressModel = new Leeaddress();
        $this->key = config('site.tengxunkey');
        //在地址管理里面
    }


    /**
     * 添加修改
     */
    public function add() {
        $param = request()->post();
        $param['uid'] = UID;

        (new AddressValidate())->goCheck(null, $param);
        Db::startTrans();
        try {
            if ($param['status'] == 1) {
                $count = $this->addressModel->where(['uid'=> UID, 'status'=> 1])->count();
                if ($count >= 1) {
                    //把其他的地址 为0
                    $this->addressModel->where(['uid'=> UID])->setField('status', 0);
                }
            }

            $id = input('id/d', 0);
            $this->addressModel->allowField(true);

            if ($id) {
                $this->addressModel->save($param, ['id'=>$id, 'uid'=> UID]);
            } else {
                $this->addressModel->data($param)->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }

        return true;
    }

    /**删除地址*/
    public function del($id = 0) {
        $where['uid'] = UID;
        $where['id'] = $id;
        $res = $this->addressModel->where($where)->delete();

        if (!$res) {
            throw new ValidateException('删除失败');
        }

        return true;
    }

    /**地址列表*/
    public function addressList() {
        $list = $this->addressModel->order('createtime desc')->where('uid', UID)->paginate();

        return $list;
    }

    /**
     * 获取默认收获地址
     */
    public function getDefault() {
        $where['uid'] = UID;
        $where['status'] = 1;
        $info = $this->addressModel->where($where)->find();

        return $info;
    }
    public function detail($id) {
        $where['uid'] = UID;
        $where['id'] = $id;
        $info = $this->addressModel->where($where)->find();

        return $info;
    }

    /**
     * 经纬度
     * $lat 纬度
     * $lng 经度
     */
    public function txCity($lat, $lng) {
        $params = [
            'location' => $lat . ',' . $lng,
            'get_poi'  => 0,
            'key'      => $this->key,
            'output'   => 'JSON'
        ];
        $res = Http::get($this->url, $params);
        $result = json_decode($res,true);

        if(isset($result['status']) && $result['status']==0){
            return $result['result']['address_component'];
        }else{
            return false;
        }

    }

}
